//
//  NSString+Html.m
//  HolyShit
//
//  Created by Robin on 2017/1/7.
//  Copyright © 2017年 HolyShit. All rights reserved.
//

#import "NSString+Html.h"

@implementation NSString (Html)

- (NSString *)replaceTagAll
{
    return [[[[[[[[self replaceTagP]
                   replaceTagH]
                   replaceTagBr]
                   replaceTagImg]
                   replaceTagSpan]
                   replaceTagTable]
                   replaceTagStrong]
                   replaceTagSpecial];
}

//替换特殊字符
- (NSString *)replaceTagSpecial
{
    //\n也替换，排版用标签就好了
    NSArray<NSString *> *orign = @[@"\n", @"&nbsp;", @"&amp;", @"&lt;", @"&gt;", @"&quot;", @"&qpos;"];
    NSArray<NSString *> *result = @[@"", @" ", @"&", @"<", @">", @"\"", @"'"];
    __block NSString *resultStr = self;
    [orign enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        resultStr = [self replaceRegStr:obj WithStr:result[idx]];
    }];
    return resultStr;
}

- (NSString *)replaceRegStr:(NSString *)regStr WithStr:(NSString *)str
{
    NSRegularExpression *regExp = [[NSRegularExpression alloc] initWithPattern:regStr options:NSRegularExpressionCaseInsensitive error:nil];
    return [regExp stringByReplacingMatchesInString:self options:NSMatchingReportProgress range:self.rangeOfAll withTemplate:str];
}

- (NSString *)replaceTagBr
{
    return [self replaceRegStr:@"<\\s*br\\s*/?>(\r\n)?" WithStr:@"\n"];
}

- (NSString *)replaceTagP
{
    return [self replaceRegStr:@"</?p>" WithStr:@"\n"];
}

- (NSString *)replaceTagSpan
{
    return [self replaceRegStr:@"</?span>" WithStr:@""];
}

- (NSString *)replaceTagImg
{
    return [self replaceRegStr:@"<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>" WithStr:@""];
}

- (NSString *)replaceTagStrong
{
    return [self replaceRegStr:@"<strong>([.\\s\\S]*?)</strong>" WithStr:@""];
}

- (NSString *)replaceTagH
{
    return [self replaceRegStr:@"<h([1-6])>([.\\s\\S]*?)</h[1-6]>" WithStr:@""];
}

- (NSString *)replaceTagTable
{
    return [self replaceRegStr:@"<table>([.\\s\\S]*?)</table>" WithStr:@""];
}

@end
